import 'dart:convert';

import 'package:flutter_deer/generated/json/base/json_field.dart';
import 'package:flutter_deer/generated/json/get_user_info_entity.g.dart';
import 'package:sp_util/sp_util.dart';

import 'package:flutter_deer/res/constant.dart';

@JsonSerializable()
class GetUserInfoEntity {
	bool? accountNonExpired = false;
	bool? accountNonLocked = false;
	int? admin = 0;
	List<GetUserInfoAuthorities>? authorities = [];
	String? clientId = '';
	String? clientType = '';
	bool? credentialsNonExpired = false;
	bool? dataAllFlag = false;
	String? deviceId = '';
	String? email = '';
	bool? enabled = false;
	String? groupMerchantCode = '';
	bool? hasOpPassword = false;
	String? id = '';
	String? loginMchId = '';
	String? loginMerchantCode = '';
	String? loginMerchantName = '';
	int? loginMerchantType = 0;
	String? merchantUserId = '';
	String? name = '';
	List<String>? needPasswordPermissions = [];
	int? orderViewPermission = 0;
	String? originSystemCode = '';
	List<String>? permissions = [];
	String? productClientType = '';
	String? productLine = '';
	String? systemCode = '';
	String? testField = '';
	String? username = '';

	GetUserInfoEntity();

	factory GetUserInfoEntity.fromJson(Map<String, dynamic> json) => $GetUserInfoEntityFromJson(json);

	Map<String, dynamic> toJson() => $GetUserInfoEntityToJson(this);

	// 存储
	void save() {
		SpUtil.putObject(Constant.userInfo, toJson());
	}

	// 读取
	static GetUserInfoEntity? get() {
		final String? jsonString = SpUtil.getString(Constant.userInfo);
		if (jsonString?.isNotEmpty != true) {
			return null;
		}

		try {
			final dynamic data = json.decode(jsonString!);
			if (data is Map<String, dynamic>) {
				return GetUserInfoEntity.fromJson(data);
			} else {
				print('解析失败：期望 Map<String, dynamic>，但返回的是 ${data.runtimeType}');
				return null;
			}
		} catch (e, stackTrace) {
			print('JSON 解析失败: $e\n$stackTrace');
			return null;
		}
	}

	// 获取deviceId
	static String getDeviceId() {
    final GetUserInfoEntity? userInfo = get();
    return userInfo?.deviceId ?? '';
  }

  @override
	String toString() {
		return jsonEncode(this);
	}
}

@JsonSerializable()
class GetUserInfoAuthorities {
	String? component = '';
	bool? hideInMenu = false;
	String? icon = '';
	String? iconType = '';
	String? label = '';
	String? name = '';
	String? path = '';
	String? redirect = '';
	List<dynamic>? routes = [];
	String? target = '';

	GetUserInfoAuthorities();

	factory GetUserInfoAuthorities.fromJson(Map<String, dynamic> json) => $GetUserInfoAuthoritiesFromJson(json);

	Map<String, dynamic> toJson() => $GetUserInfoAuthoritiesToJson(this);

	@override
	String toString() {
		return jsonEncode(this);
	}
}